package br.ita.redecasd.mi.ldap;

import java.util.Hashtable;

import static br.ita.redecasd.mi.ldap.LDAPConstants.*;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;



public class LDAPManager {
	
	private DirContext ctx;
	
	public LDAPManager() throws NamingException
	{
		Hashtable<String,String> env = new Hashtable<String,String>();
		env.put( Context.INITIAL_CONTEXT_FACTORY, INITIAL_CTX );
		env.put( Context.PROVIDER_URL, PROVIDER_URL );
		ctx = new InitialDirContext(env);
	}
	
	public byte[] getCertificateBin( String username ) throws NamingException
	{
		String query = "cn=" + username +",ou=comp";
		String attributesWanted[] = { "userCertificate" };
		NamingEnumeration certs = ctx.getAttributes(query, attributesWanted ).getAll();
		
		while( certs.hasMore() )
		{
			 Attribute attr = (Attribute)certs.next();
             byte[] certInBin = (byte[]) attr.get();
             return certInBin;
		}
		
		return null;
	}
	
	public String[] getPatientDetails( String login ) throws NamingException
	{
		String query = "cn=" + login + ",ou=comp";
		String attributesWanted[] = { "displayName", "homePhone", "postalAddress" };
		NamingEnumeration en = ctx.getAttributes(query, attributesWanted).getAll();
		while (en.hasMore() )
		{
			Attribute cnAttr = (Attribute)en.next();
			String name = (String)cnAttr.get();
			Attribute phoneAttr = (Attribute)en.next();
			String phoneNumber = (String)phoneAttr.get();
			Attribute addrAttr = (Attribute)en.next();
			String address = (String)addrAttr.get();
			String[] info = { login, name, phoneNumber, address };
			return info;
			
		}
		
		return null;
	}
	
	
	
	
	
	
}
